#ifndef NETLIB_TIMESTAMP_H
#define NETLIB_TIMESTAMP_H

// 时间戳类-管理与时间相关的内容
// Linux时间纪元 1970-01-01 00：00：00

#include "copyable.h"
#include "Types.h"

#include <boost/operators.hpp>

namespace netlib
{
/*
copyable（空基类、标识类）：值语义，可以拷贝，拷贝后与原对象脱离关系，相互独立
noncopyable：对象语义，一般不能拷贝，即使某些情况下能拷贝，也会与原对象有一定的关系，如共享资源
less_than_comparable：boost模板库，当类中自己定义了operator<后，该模板自动重载定义>、>=、<=符号
*/

class Timestamp : public netlib::copyable,
                  public boost::equality_comparable<Timestamp>,
                  public boost::less_than_comparable<Timestamp>
{
public:
    Timestamp() : microSecondsSinceEpoch_(0)
    { }

    explicit Timestamp(int64_t microSecondsSinceEpochArg)
        : microSecondsSinceEpoch_(microSecondsSinceEpochArg)
    { }

    void swap(Timestamp& that)
    {
        std::swap(microSecondsSinceEpoch_, that.microSecondsSinceEpoch_);
    }

    string toString() const;
    
    string toFormattedString(bool showMicroseconds = true) const;

    bool valid() const { return microSecondsSinceEpoch_ > 0; }

    int64_t microSecondsSinceEpoch() const { return microSecondsSinceEpoch_; }

    time_t secondsSinceEpoch() const
    {
        return static_cast<time_t>(microSecondsSinceEpoch_ / kMicroSecondsPerSecond);
    }

    static Timestamp now(); // 返回当前时间

    static Timestamp invalid() { return Timestamp(); } // 返回一个时间为0的对象

    static Timestamp fromUnixTime(time_t t) { return fromUnixTime(t, 0); }

    static Timestamp fromUnixTime(time_t t, int microseconds) // 返回一个设定秒数的对象
    {
        return Timestamp(static_cast<int64_t>(t) * kMicroSecondsPerSecond + microseconds);
    }

    static const int kMicroSecondsPerSecond = 1000 * 1000; // 换算单位，微秒转秒要除以1000000

private:
    int64_t microSecondsSinceEpoch_; //微秒，距离时间纪元所过的时间

}; // class Timestamp end



inline bool operator<(Timestamp lhs, Timestamp rhs) // >、>=、<=通过模板库自动实现
{
    return lhs.microSecondsSinceEpoch() < rhs.microSecondsSinceEpoch();
}

inline bool operator==(Timestamp lhs, Timestamp rhs)
{
    return lhs.microSecondsSinceEpoch() == rhs.microSecondsSinceEpoch();
}

inline double timeDifference(Timestamp high, Timestamp low) // 计算两时间之差
{
    int64_t diff = high.microSecondsSinceEpoch() - low.microSecondsSinceEpoch();
    return static_cast<double>(diff) / Timestamp::kMicroSecondsPerSecond; // 返回单位为秒
}


inline Timestamp addTime(Timestamp timestamp, double seconds) // 增加seconds秒
{
    int64_t delta = static_cast<int64_t>(seconds * Timestamp::kMicroSecondsPerSecond);
    return Timestamp(timestamp.microSecondsSinceEpoch() + delta);
}

}  // namespace netlib end

#endif